#include "command.h"

/* it can move file or dir which is int absolute path */

int _mv(char *argv[])
{
	/* check the number of cmd-line parameters is correct */
	int argc = 0;
	for (char **ptr = argv; *ptr != NULL; ptr++)
		argc++;

	if (argc < 3) {
		fprintf(stderr, "Usage: mv file1/dir1 file2/dir2\n");
		return -1;
	}
	
	const char *src;
	char dest[FILEPATH_SIZE];
	if (argc > 3 && is_dir(argv[argc - 1]) != 1) {
		fprintf(stderr, "mv error: %s is not a directory\n", argv[argc - 1]);
		return -1;
	}

	for (int i = 1; i < argc - 1; i++) {
		src = argv[i];
		if (is_dir(argv[argc - 1]) == 1)
			snprintf(dest, sizeof(dest), "%s/%s", argv[argc - 1], src);
		else 
			snprintf(dest, sizeof(dest), "%s", argv[argc - 1]);

		if (access(src, F_OK) == -1) {
			fprintf(stderr, "mv error: source file does not exist\n");
			return -1;
		}
		if (rename(src, dest) == -1) {
			fprintf(stderr, "mv error: rename\n");
			return -1;
		}
	}

	return 0;
}
